package com.xjrsoft.module.form.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.yulichang.base.MPJBaseServiceImpl;
import com.xjrsoft.common.enums.YesOrNoEnum;
import com.xjrsoft.common.exception.MyException;
import com.xjrsoft.module.form.dto.FormHistoryChangeDto;
import com.xjrsoft.module.form.entity.FormDesignConfig;
import com.xjrsoft.module.form.entity.FormHistory;
import com.xjrsoft.module.form.entity.FormTemplate;
import com.xjrsoft.module.form.mapper.FormHistoryMapper;
import com.xjrsoft.module.form.mapper.FormTemplateMapper;
import com.xjrsoft.module.form.service.IFormHistoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xjrsoft.module.generator.entity.TableConfig;
import com.xjrsoft.module.workflow.entity.WorkflowSchemaHistory;
import com.xjrsoft.module.workflow.vo.ProcessChangeVo;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

/**
 * <p>
 * 自定义表单历史表  每次修改自定义表单会新增一条数据 服务实现类
 * </p>
 *
 * @author tzx
 * @since 2022-05-09
 */
@Service
@AllArgsConstructor
public class FormHistoryServiceImpl extends MPJBaseServiceImpl<FormHistoryMapper, FormHistory> implements IFormHistoryService {

    private final FormHistoryMapper formHistoryMapper;

    private final FormTemplateMapper formTemplateMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    @SneakyThrows
    public Boolean change(FormHistoryChangeDto dto) {

        //全部设置为非活动版本
        LambdaQueryWrapper<FormHistory> wrapper = Wrappers.lambdaQuery(FormHistory.class).eq(FormHistory::getFormId, dto.getFormId());
        FormHistory formHistory1 = new FormHistory();
        formHistory1.setActivityFlag(YesOrNoEnum.NO.getCode());
        formHistoryMapper.update(formHistory1, wrapper);

        //把选择的版本设置为活动版本
        FormHistory formHistory = formHistoryMapper.selectById(dto.getId());
        formHistory.setActivityFlag(YesOrNoEnum.YES.getCode());
        formHistoryMapper.updateById(formHistory);

        //更新formTemplate表的数据
        LambdaQueryWrapper<FormTemplate> formTemplateLambdaQuery = Wrappers.lambdaQuery(FormTemplate.class).eq(FormTemplate::getId, dto.getFormId());
        FormTemplate formTemplate = new FormTemplate();
        formTemplate.setFormJson(formHistory.getFormJson());
        formTemplateMapper.update(formTemplate,formTemplateLambdaQuery);

        return true;
    }
}
